package com.yh.consumer.Controller;

import com.yh.consumer.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
public class MovieController {

    private  static  final Logger logger = LoggerFactory.getLogger(MovieController.class);
    @Autowired
    private RestTemplate restTemplate;

    //@Autowired
    //private DiscoveryClient discoveryClient;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 简单通过restTemplate调用远程微服务API
     * 访问地址：http://localhost:8001/user/1
     * @param id
     * @return
     */
    @GetMapping("user/{id}")
    public User findOneUser(@PathVariable Long id){
        //只能访问IP+端口对应的服务
        //return  restTemplate.getForObject("http://localhost:8000/findOneUser/"+id,User.class);
        //改为使用虚拟主机名称(eureka和ribbon配合使用时才能使用虚拟主机名，可以按照负载规则请求该服务名下的所有服务)
        return  restTemplate.getForObject("http://spring-cloud-provider-user/findOneUser/"+id,User.class);
    }

    /**
     * 通过使用discoveryClient 获取提供者微服务的应用信息（包含自定义元数据）
     * 这里可以看到当前选择的是哪个节点。
     * @return
     */
    @GetMapping("log-instance")
    public ServiceInstance logInstance(){
        // return discoveryClient.getInstances("spring-cloud-user-provider");
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("spring-cloud-provider-user");
        logger.info("当前选择的节点： ServiceId:{}, Host{}, Port: {}.",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
        return  serviceInstance;
    }
}
